package main

import (
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"log"
	"my_exporter/config"
	"my_exporter/exporter"
	"net/http"
	"os"
	"path/filepath"
)

func main() {
	cfg := config.ParseFlags()
	if cfg.ShowVersion {
		log.Printf("my_exporter version %s (build date: %s, git commit: %s)\n", config.Version, config.BuildDate, config.GitCommit)
		os.Exit(0)
	}

	// 设置日志文件
	logPath := cfg.LogPath
	if err := os.MkdirAll(logPath, 0755); err != nil {
		log.Fatalf("can not create log path: %s", logPath)
		os.Exit(0)
	}
	logPathFile := filepath.Join(logPath, "my_exporter.log")
	logFile, err := os.OpenFile(logPathFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		log.Fatalf("can not create log file: %s %v", logPathFile, err)
		os.Exit(0)
	}
	defer logFile.Close()

	// 设置日志输出到文件
	log.SetOutput(logFile)

	// Initial data collection
	log.Printf("my exporter start...")
	log.Printf("config is: %v", cfg)

	//getTopData(cfg)
	//getTopMemoryData(cfg)

	// pprof
	if cfg.Pprof {
		go func() {
			http.ListenAndServe(cfg.Pprofaddr, nil)
		}()
	}

	// 创建自定义 Collector
	customCollector := exporter.NewCustomCollector(cfg.TopProcesses)

	// 注册到默认注册表
	prometheus.MustRegister(customCollector)

	//// 模拟记录一些HTTP请求
	//go func() {
	//	for {
	//		methods := []string{"GET", "POST", "PUT", "DELETE"}
	//		statuses := []string{"200", "404", "500"}
	//		customCollector.RecordRequest(
	//			methods[rand.Intn(len(methods))],
	//			statuses[rand.Intn(len(statuses))],
	//		)
	//		time.Sleep(time.Second)
	//	}
	//}()

	// 设置HTTP处理
	http.Handle(cfg.MetricsPath, promhttp.Handler())
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`<html>
			<head><title>Custom Collector Example</title></head>
			<body>
			<h1>Custom Collector Example</h1>
			<p><a href="/metrics">Metrics</a></p>
			</body>
			</html>`))
	})

	// 启动HTTP服务器
	log.Printf("Starting server on %s", cfg.ListenAddr)
	http.ListenAndServe(cfg.ListenAddr, nil)
}
